import { post } from "@/util/request";
let uploadFilesTime: any = null;
// 获取系统时间
export const SysTime = async () => {
  const obj = await post("/SystemApi/SysTime");
  uni.setStorageSync("utcOffsetMinutes", obj.utcOffsetMinutes);
  return obj;
};
// 获取弹窗公告
export const SysNoticePopup = async () => {
  const obj = await post("/SystemApi/SysNoticePopup");
  return obj;
};


export const UploadTokenApi = async (data: any) => {
  const obj = await post("/SystemApi/UploadToken", data);
  console.log("进入了");
  console.log(JSON.stringify(obj));

  return obj;
};
// 临时文件上传
// count 上传数量
// file_purpose 1头像  2聊天
// type 上传类型  album camera video
// 临时文件上传
export const UploadToken = async (
  count: number = 1,
  file_purpose: number,
  type: string
): Promise<any> => {
  return new Promise((resolve, reject) => {
    const chooseFile = type === "video" ? uni.chooseVideo : uni.chooseImage;
    chooseFile({
      count,
      sourceType: [type],
      success: async (res: any) => {
        let file_suffix: any = "";
        /*#ifdef APP-PLUS*/
        file_suffix =
          type === "video" ? res.tempFilePath : res.tempFilePaths[0];
        /*#endif*/
        /*#ifdef H5*/
        file_suffix = type === "video" ? res.name : res.tempFiles[0].name;
        /*#endif*/
        file_suffix = file_suffix.split(".").pop();
        const tempFiles = res.tempFiles.map((file: any) => ({
          path: file.path,
          size: file.size,
          file_suffix: file_suffix,
        }));

        let i: number = 0;
        let lastUpdateTime = Date.now(); // 记录上次更新时间
        uni.showLoading({
          title: `0%`,
          mask: true,
        });

        // 获取上传 Token
        try {
          uploadFilesTime = setInterval(() => {
            i += 3;
            const currentTime = Date.now();
            if (currentTime - lastUpdateTime >= 500) {
              lastUpdateTime = currentTime;
              uni.showLoading({
                title: `${Math.min(i, 99)}%`,
                mask: true,
              });
            }

            if (i >= 100) {
              clearInterval(uploadFilesTime);
              uni.showLoading({
                title: "99%",
                mask: true,
              });
            }
          }, 500);

          let obj = await UploadTokenApi({
            file_suffix,
            file_purpose,
          });
          let sizeObj = {};
          obj = { ...obj, uploadUrl: atob(obj.uploadurl), type, ...sizeObj };

          for (let index = 0; index < tempFiles.length; index++) {
            const file = tempFiles[index];
            try {
              /*#ifdef APP-PLUS*/
              await handleFileUploadForApp(file, obj);
              /*#endif*/
              /*#ifdef H5*/
              await handleFileUploadForH5(file, obj);
              /*#endif*/
              console.log(`第 ${index + 1} 个文件上传成功:`, obj);
              console.log(`上传的文件信息:`, file);
            } catch (error) {
              console.error(`第 ${index + 1} 个文件上传失败:`, file, error);
            }
          }

          clearInterval(uploadFilesTime);
          uni.hideLoading(); // 上传完成隐藏 loading
          resolve(obj); // 上传完成后返回对象
        } catch (error) {
          clearInterval(uploadFilesTime);
          uni.hideLoading(); // 上传失败隐藏 loading
          console.error("上传失败:", error);
          uni.showToast({ title: "上传失败" });
          reject(error);
        }
      },
      fail: (err) => {
        clearInterval(uploadFilesTime);
        uni.hideLoading(); // 选择文件失败隐藏 loading
        reject(err);
      },
    });
  });
};

// H5 文件上传
export const handleFileUploadForH5 = async (file: any, obj: any) => {
  const blobUrl = file.path;
  console.log(blobUrl);
  const response = await fetch(blobUrl);
  const blob = await response.blob();

  const reader = new FileReader();
  return new Promise<any>((resolve, reject) => {
    reader.onloadend = async () => {
      const arrayBuffer = reader.result;
      try {
        await uploadFileToServer({ ...obj, arrayBuffer });
        resolve(obj); // 确保返回结果
      } catch (error) {
        console.error("H5 文件上传失败:", error);
        reject(error);
      }
    };

    reader.onerror = (error) => {
      console.error("文件读取失败:", error);
      reject(error);
    };

    reader.readAsArrayBuffer(blob);
  });
};

// App 文件上传
export const handleFileUploadForApp = async (file: any, obj: any) => {
  let blobUrl = file.path;
  console.log(blobUrl);

  return new Promise<any>(async (resolve, reject) => {
    // 判断 file.path 是否是 Base64 字符串
    const isBase64 = blobUrl.startsWith("data:");
    if (isBase64) {
      const arrayBuffer = await base64ToArrayBuffer(blobUrl.split(",")[1]); // 截取 Base64 数据部分
      console.log("222arrayBuffer---", arrayBuffer);

      uploadFileToServer({ ...obj, arrayBuffer })
        .then(() => resolve(obj))
        .catch((error) => {
          console.error("上传文件失败:", error);
          reject(error);
        });
    } else {
      // 如果不是 Base64 字符串，则处理本地文件路径
      plus.io.resolveLocalFileSystemURL(blobUrl, (entry: any) => {
        entry.file((file: any) => {
          const fileReader: any = new plus.io.FileReader();
          fileReader.readAsDataURL(file);

          fileReader.onloadend = async () => {
            try {
              const dataURL = fileReader.result;
              const arrayBuffer = await base64ToArrayBuffer(
                dataURL.split(",")[1]
              );
              console.log("arrayBuffer---", arrayBuffer);

              await uploadFileToServer({ ...obj, arrayBuffer });
              resolve(obj); // 确保返回结果
            } catch (error) {
              console.error("App 文件上传失败:", error);
              reject(error);
            }
          };

          fileReader.onerror = (error: any) => {
            console.error("读取文件失败:", error);
            reject(error);
          };
        });
      });
    }
  });
};

// 上传文件到服务器
export const uploadFileToServer = async (obj: any) => {
  console.log("上传文件到服务器", obj.arrayBuffer);
  return new Promise<void>((resolve, reject) => {
    uni.request({
      url: obj.uploadUrl,
      method: "PUT",
      header: { "Content-Type": "application/octet-stream" },
      data: obj.arrayBuffer,
      success: (uploadRes) => {
        console.log("上传成功:", uploadRes);
        resolve();
      },
      fail: (uploadError) => {
        uni.showToast({ title: "上传失败" });
        console.error("上传失败:", uploadError);
        reject(uploadError);
      },
    });
  });
};

// 将 Base64 字符串转换为 ArrayBuffer
export const base64ToArrayBuffer = async (
  base64: string
): Promise<ArrayBuffer> => {
  try {
    const binaryString = atob(base64);
    const length = binaryString.length;
    const arrayBuffer = new ArrayBuffer(length);
    const uintArray = new Uint8Array(arrayBuffer);
    for (let i = 0; i < length; i++) {
      uintArray[i] = binaryString.charCodeAt(i);
    }
    return arrayBuffer;
  } catch (e) {
    console.error("Base64 解码失败:", e);
    throw e;
  }
};

// 提现设置
export const WithdrawalConfig = async () => {
  const obj = await post("/SystemApi/WithdrawalConfig");
  uni.setStorageSync("WithdrawalConfig", obj);

  return obj;
};
// 注册设置
export const RegisterConfig = async () => {
  const obj = await post("/SystemApi/RegisterConfig");
  uni.setStorageSync("RegisterConfig", obj);

  return obj;
};
export const WebRtcConfig = async () => {
  const obj = await post("/SystemApi/WebRtcConfig");
  uni.setStorageSync("WebRtcConfig", obj);
  return obj;
};

// 提现日志
export const WithdrawalLog = async () => {
  const obj = await post("/SystemApi/WithdrawalLog");
  uni.setStorageSync("WebRtcConfig", obj);
  return obj;
};
// 首页统计
export const IndexStatistics = async () => {
  const obj = await post("/SystemApi/IndexStatistics");
  uni.setStorageSync("WebRtcConfig", obj);
  return obj;
};


// 系统公告列表
export const SysNotice = async (data:any) => {
  const obj = await post("/SystemApi/SysNotice",data);
  return obj;
};

export const WebSiteConfig = async () => {
  const obj = await post("/SystemApi/WebSiteConfig");
  uni.setStorageSync("WebSiteConfig", obj);
  return obj;
};

